// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.apache.doris.nereids.trees.expressions.functions.agg;

import org.apache.doris.catalog.FunctionSignature;
import org.apache.doris.nereids.exceptions.AnalysisException;
import org.apache.doris.nereids.trees.expressions.Expression;
import org.apache.doris.nereids.trees.expressions.OrderExpression;
import org.apache.doris.nereids.trees.expressions.functions.ExplicitlyCastableSignature;
import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
import org.apache.doris.nereids.types.DataType;
import org.apache.doris.nereids.types.VarcharType;
import org.apache.doris.nereids.types.coercion.AnyDataType;
import org.apache.doris.nereids.util.ExpressionUtils;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;

import java.util.List;

/**
 * AggregateFunction 'group_concat'. This class is generated by GenerateFunction.
 */
public class GroupConcat extends NullableAggregateFunction
        implements ExplicitlyCastableSignature {

    public static final List<FunctionSignature> SIGNATURES = ImmutableList.of(
            FunctionSignature.ret(VarcharType.SYSTEM_DEFAULT).args(VarcharType.SYSTEM_DEFAULT),
            FunctionSignature.ret(VarcharType.SYSTEM_DEFAULT)
                    .varArgs(VarcharType.SYSTEM_DEFAULT, AnyDataType.INSTANCE_WITHOUT_INDEX),
            FunctionSignature.ret(VarcharType.SYSTEM_DEFAULT)
                    .varArgs(VarcharType.SYSTEM_DEFAULT, VarcharType.SYSTEM_DEFAULT, AnyDataType.INSTANCE_WITHOUT_INDEX)
    );

    private final int nonOrderArguments;

    /**
     * constructor with 1 argument.
     */
    public GroupConcat(boolean distinct, boolean alwaysNullable, Expression arg, OrderExpression... orders) {
        super("group_concat", distinct, alwaysNullable, ExpressionUtils.mergeArguments(arg, orders));
        this.nonOrderArguments = 1;
        checkArguments();
    }

    /**
     * constructor with 1 argument.
     */
    public GroupConcat(boolean distinct, Expression arg, OrderExpression... orders) {
        this(distinct, false, arg, orders);
    }

    /**
     * constructor with 1 argument, use for function search.
     */
    public GroupConcat(Expression arg, OrderExpression... orders) {
        this(false, arg, orders);
    }

    /**
     * constructor with 2 arguments.
     */
    public GroupConcat(boolean distinct, boolean alwaysNullable,
            Expression arg0, Expression arg1, OrderExpression... orders) {
        super("group_concat", distinct, alwaysNullable, ExpressionUtils.mergeArguments(arg0, arg1, orders));
        this.nonOrderArguments = 2;
        checkArguments();
    }

    /**
     * constructor with 2 arguments.
     */
    public GroupConcat(boolean distinct, Expression arg0, Expression arg1, OrderExpression... orders) {
        this(distinct, false, arg0, arg1, orders);
    }

    /**
     * constructor with 2 arguments, use for function search.
     */
    public GroupConcat(Expression arg0, Expression arg1, OrderExpression... orders) {
        this(false, arg0, arg1, orders);
    }

    /**
     * constructor for always nullable.
     */
    public GroupConcat(boolean distinct, boolean alwaysNullable, int nonOrderArguments, List<Expression> args) {
        super("group_concat", distinct, alwaysNullable, args);
        this.nonOrderArguments = nonOrderArguments;
        checkArguments();
    }

    @Override
    public boolean nullable() {
        return alwaysNullable || children().stream()
                .anyMatch(expression -> !(expression instanceof OrderExpression) && expression.nullable());
    }

    @Override
    public List<Expression> getDistinctArguments() {
        if (distinct) {
            return ImmutableList.of(getArgument(0));
        } else {
            return ImmutableList.of();
        }
    }

    @Override
    public void checkLegalityBeforeTypeCoercion() {
        DataType typeOrArg0 = getArgumentType(0);
        if (!typeOrArg0.isStringLikeType() && !typeOrArg0.isNullType()) {
            throw new AnalysisException(
                    "group_concat requires first parameter to be of type STRING: " + this.toSql());
        }

        if (nonOrderArguments == 2) {
            DataType typeOrArg1 = getArgumentType(1);
            if (!typeOrArg1.isStringLikeType() && !typeOrArg1.isNullType()) {
                throw new AnalysisException(
                        "group_concat requires second parameter to be of type STRING: " + this.toSql());
            }
        }
    }

    @Override
    public GroupConcat withAlwaysNullable(boolean alwaysNullable) {
        return new GroupConcat(distinct, alwaysNullable, nonOrderArguments, children);
    }

    /**
     * withDistinctAndChildren.
     */
    @Override
    public GroupConcat withDistinctAndChildren(boolean distinct, List<Expression> children) {
        Preconditions.checkArgument(children().size() >= 1);
        boolean foundOrderExpr = false;
        int firstOrderExrIndex = 0;
        for (int i = 0; i < children.size(); i++) {
            Expression child = children.get(i);
            if (child instanceof OrderExpression) {
                foundOrderExpr = true;
            } else if (!foundOrderExpr) {
                firstOrderExrIndex++;
            } else {
                throw new AnalysisException("invalid group_concat parameters: " + children);
            }
        }

        List<OrderExpression> orders = (List) children.subList(firstOrderExrIndex, children.size());
        if (firstOrderExrIndex == 1) {
            return new GroupConcat(distinct, alwaysNullable,
                    children.get(0), orders.toArray(new OrderExpression[0]));
        } else if (firstOrderExrIndex == 2) {
            return new GroupConcat(distinct, alwaysNullable,
                    children.get(0), children.get(1), orders.toArray(new OrderExpression[0]));
        } else {
            throw new AnalysisException("group_concat requires one or two parameters: " + children);
        }
    }

    @Override
    public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
        return visitor.visitGroupConcat(this, context);
    }

    @Override
    public List<FunctionSignature> getSignatures() {
        return SIGNATURES;
    }

    public MultiDistinctGroupConcat convertToMultiDistinct() {
        Preconditions.checkArgument(distinct,
                "can't convert to multi_distinct_group_concat because there is no distinct args");
        return new MultiDistinctGroupConcat(alwaysNullable, nonOrderArguments, children);
    }

    // TODO: because of current be's limitation, we have to thow exception for now
    // remove this after be support new method of multi distinct functions
    private void checkArguments() {
        if (isDistinct() && children().stream().anyMatch(expression -> expression instanceof OrderExpression)) {
            throw new AnalysisException(
                    "group_concat don't support using distinct with order by together");
        }
    }
}
